import { defineComponent, ref, reactive, computed, watch } from "vue";
import styles from "./menu-sider.module.less";
import useNavigator from "@/hooks/useNavigator";
import { useStore as useMenuStore } from "@/store/menu";
import { judgeAuth } from "@/auth/checkAuth";
const project_name = require('@/config/main').project_name;
export default defineComponent({
  name: 'menu-sider',
  props: ['collapsed'],
  setup(props: any) {
    const navigator = useNavigator();
    const menuStore = useMenuStore();
    // 扁平化处理
    const eachRouteFlat = (arr: any[], arr2: any[]) => {
      arr.forEach((x: any) => {
        arr2.push(x);
        x?.children?.length > 0 && eachRouteFlat(x.children, arr2);
      })
    }
    // 路由列表
    const route_list: any[] = navigator?.options?.routes?.find(x => x.name === 'index')?.children ?? [];
    // 扁平化路由列表
    let flat_route_list: any[] = [];
    eachRouteFlat(route_list, flat_route_list);
    // 菜单列表
    const menu_list: any[] = menuStore.state.menu_list ?? [];
    // 判断是否有可显示子菜单
    const hasVisibleMenuC = (item: any) => {
      // 不是目录不需要判断子菜单
      if(item.menu_type === 'C') {
        return true;
      }
      let bol = false;
      const eachCheckVisible = (t: any) => {
        if (t.menu_type === 'M') {
          t.childlist?.forEach((x: any) => {
            if ([x.menu_type === 'C', Boolean(Number(x.visible)), Number(x.status), judgeAuth(x.perms || '')].every(y => !!y)) {
              bol = true;
            }
            eachCheckVisible(x);
          })
        }
      }
      eachCheckVisible(item);
      return bol;
    }
    // 菜单关联路由
    const eachMap = (arr: any[]) => {
      arr.forEach((item: any) => {
        item.route = flat_route_list.find(x => x.name === item.path);
        // 不显示、停用、无权限的菜单项皆不显示, 无可显示子菜单的目录项也不显示
        item.visible = [Boolean(Number(item.visible)), Number(item.status), judgeAuth(item.perms || ''), hasVisibleMenuC(item)].every(x => !!x);
        item.childlist?.length > 0 && eachMap(item.childlist);
      })
    }
    eachMap(menu_list);
    // 菜单排序
    const eachSort = (arr: any[]) => {
      arr = arr.sort((a, b) => a.order_num - b.order_num);
      arr.forEach((item: any) => {
        item.childlist?.length > 0 && eachSort(item.childlist);
      })
    }
    eachSort(menu_list);
    // 扁平化处理
    const eachMenuFlat = (arr: any[], arr2: any[]) => {
      arr.forEach((x: any) => {
        arr2.push(x);
        x?.childlist?.length > 0 && eachMenuFlat(x.childlist, arr2);
      })
    }
    // 扁平化菜单列表
    let flat_menu_list: any[] = [];
    eachMenuFlat(menu_list, flat_menu_list);
    // 大屏菜单
    const largeSreenMenu = reactive({
      menu_total: [],
    } as any)
    // 设置大屏菜单内容
    largeSreenMenu.menu_total = menu_list;
    // 拥有激活状态菜单项
    const hasActiveChild = (e: any) => {
      return navigator.route.matched.map(x => x.name).includes(e.path);
    }
    // 当前激活总菜单项
    const menuTotalActive = computed(() => {
      return largeSreenMenu.menu_total.find((x: any) => hasActiveChild(x));
    })
    // 当前激活总菜单项下属菜单
    const largeSreenMenuChild = computed(() => {
      return menu_list?.find?.(x => x.path === menuTotalActive?.value?.path)?.childlist || [];
    })
    // 跳转
    const navTo = (item: { [key: string]: any }) => {
      if (item?.is_frame) {
        // 外链
        window.open(item.path);
      } else {
        if (item.path === navigator.route.name) {
          return;
        }
        navigator.push({
          name: item.path,
        })
      }
    }
    // 打开的菜单
    const openKeys = ref([] as any);
    // 选中的菜单
    const selectedKeys = ref([] as any);
    // 设置打开的菜单
    const setOpenKeys = () => {
      openKeys.value = navigator.route.matched.map(x => x.name);
    }
    // 监听路由变化，对应激活菜单项
    watch(() => navigator.route, (nv, ov) => {
      if (nv?.meta?.activeMenu) {
        selectedKeys.value = [nv?.meta?.activeMenu];
      } else {
        selectedKeys.value = [nv.name];
      }
      setOpenKeys();
    }, {
      immediate: true,
      deep: true,
    });
    // 子菜单
    const MenuChild = () => (
      <>
        <a-menu
          v-model={[openKeys.value, 'openKeys']}
          class={styles.menuChild}
          selectedKeys={selectedKeys.value}
          theme="dark"
          mode="inline"
        >
          {
            largeSreenMenuChild.value.map((x: any) => (
              Boolean(Number(x?.visible)) && <MenuItem item={x} />
            ))
          }
        </a-menu>
      </>
    );

    // 菜单项
    const MenuItem: any = ({ item }: any) => {
      switch (item.menu_type) {
        case 'M':
          return (
            <a-sub-menu key={item.path} v-slots={{
              title: () => <span title={item?.menu_name}>{item?.menu_name}</span>,
              icon: () => item.route?.meta?.icon && <item.route.meta.icon />,
            }}>
              {
                item.childlist?.map((y: any) => <MenuItem item={y} />)
              }
            </a-sub-menu>
          );
        case 'C':
          return (
            Boolean(Number(item?.visible)) && <a-menu-item key={item.path} onClick={() => navTo(item)}>
              {
                item.route?.meta?.icon && <item.route.meta.icon />
              }
              <span title={item?.menu_name}>{item?.menu_name}</span>
            </a-menu-item>
          );
      }
    };

    // 打开的菜单
    const openKeys2 = ref([] as any);
    // 选中的菜单
    const selectedKeys2 = ref([] as any);
    // 设置打开的菜单
    const setOpenKeys2 = () => {
      openKeys2.value = navigator.route.matched.map(x => x.name);
    }
    // 监听路由变化，对应激活菜单项
    watch(() => navigator.route, (nv, ov) => {
      if (nv?.meta?.activeMenu) {
        selectedKeys2.value = [nv?.meta?.activeMenu];
      } else {
        selectedKeys2.value = [nv.name];
      }
      setOpenKeys2();
    }, {
      immediate: true,
      deep: true,
    });

    // 小屏菜单
    const Menu = () => (
      <a-menu
        v-model={[openKeys2.value, 'openKeys']}
        class={styles.menu}
        selectedKeys={selectedKeys2.value}
        theme="dark"
        mode="inline"
      >
        {
          menu_list.map(x => (
            Boolean(Number(x?.visible)) && <MenuItemSimple item={x} />
          ))
        }
      </a-menu>
    )

    // 小屏菜单项
    const MenuItemSimple: any = ({ item }: any) => {
      switch (item.menu_type) {
        case 'M':
          return (
            <a-sub-menu key={item.path} v-slots={{
              title: () => item?.menu_name,
              icon: () => item.route?.meta?.icon && <item.route.meta.icon />,
            }}>
              {
                item.childlist.map((y: any) => <MenuItemSimple item={y} />)
              }
            </a-sub-menu>
          );
        case 'C':
          return (
            Boolean(Number(item?.visible)) && <a-menu-item key={item.path} onClick={() => navTo(item)}>
              {
                item?.route?.meta?.icon && <item.route.meta.icon />
              }
              <span title={item?.menu_name}>{item?.menu_name}</span>
            </a-menu-item>
          );
      }
    }
    // 大屏菜单
    const LargeScreenMenu = () => (
      <>
        <div class={styles['menu-total']}>
          <div class={styles.logo} onClick={() => navigator.push({ name: 'index' })}>
            <img src={require("@/assets/image/logo.png")} />
          </div>
          <div class={styles['menu-total-list']}>
            {
              largeSreenMenu.menu_total.map((x: any) => (
                Boolean(Number(x.visible)) && <>
                  <div class={[styles['menu-total-item'], hasActiveChild(x) && styles['actived']]} onClick={() => navTo(x)}>
                    {x.route?.meta?.icon && <x.route.meta.icon class={styles.icon} />}
                    <span class={styles['menu-title']}>{x?.menu_name}</span>
                  </div>
                </>
              ))
            }
          </div>
        </div>
        <a-layout-sider
          id="sider"
          width={200}
          collapsedWidth={0}
          class={styles['menu-children']}
          v-model={[props.collapsed, 'collapsed']}
          trigger={null}
          collapsible
        >
          <div class={[styles['menu-children-container'], props.collapsed ? styles['hidden'] : styles['show']]}>
            <div class={styles['project-name']}>{project_name}</div>
            <div class={styles['parent-name']}>{menuTotalActive?.value?.menu_name || ''}</div>
            {
              largeSreenMenuChild.value.filter((x: any) => Boolean(Number(x.visible))).length > 0 ? <MenuChild /> : <div class={styles.noMenu}>无子菜单或您无权限</div>
            }
          </div>
        </a-layout-sider>
      </>
    )
    // 小屏菜单
    const SimpleScreenMenu = () => (
      <>
        <a-layout-sider
          id="sider"
          width={256}
          class={styles.simpleScreenMenu}
          trigger={null}
          collapsible
        >
          <div class={styles.logo} onClick={() => navigator.push({ name: 'index' })}>
            <img src={require("@/assets/image/logo.png")} />
            <span>{project_name}</span>
          </div>
          <Menu />
        </a-layout-sider>
      </>
    )

    const Components = () => (
      !props.collapsed ? <LargeScreenMenu /> : <SimpleScreenMenu />
    )
    return {
      menuTotalActive,
      largeSreenMenuChild,
      Components,
    }
  },
  render() {
    return <this.Components></this.Components>
  },
})